package com.learn.dubbo.core.util;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * 日期工具类
 * @author 林彬
 * @version 1.0
 */
public class DateUtil {
	
	private static Logger log = Logger.getLogger(DateUtil.class);
	
	/**
	 * 根据一个格式返回当前系统时间
	 * @param format
	 * @return
	 */
	public static String current(String format) {
		DateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(new Date());
	}
	
	/**
	 * set string to date 
	 * @param date
	 * @param format
	 * @return
	 */
	public static Date parseDate(String date, String format){
		if(StringUtils.isNotEmpty(date)){
			try {
				return new SimpleDateFormat(format).parse(date);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * @author 林彬
	 * 日期转换成字符型的
	 * @param date
	 * @param formate
	 * @return
	 */
	public static String formateDate(Date date, String formate){
		return new SimpleDateFormat(formate).format(date);
	}
	
	/**
	 * {@link #current(String)}
	 * @return
	 */
	public static String current() {
		return current("yyyyMMddHHmmss");
	}
	
	/**
	 * 将一个字符串类型的时间转换为另一种格式的字符串类型时间
	 * Example : String formattedDate = DateUtil.format("20070906112351", "yyyyMMddHHmmss", "yyyy年MM月dd日 HH时mm分ss秒")
	 * @param date 字符串时间.例如20070906112351
	 * @param sourceFormat 源时间的格式,上面为yyyyMMddHHmmss
	 * @param transFormat 要转换的目标格式
	 * @return
	 */
	public static String format(String date, String sourceFormat, String transFormat) {
		if (date==null||date.equals("")) {
			return "";
		}
		
		DateFormat _formater1 = new SimpleDateFormat(sourceFormat);
		DateFormat _formater2 = new SimpleDateFormat(transFormat);
		
		try {
			return _formater2.format(_formater1.parse(date));
		}
		catch (ParseException pe) {
			return date;
		}
	}
	
	/**
	 * 判断一个时间是否为上午
	 * @return boolean
	 */
	public static boolean isAM(Date date) {
		log.info("判断是否为上午的时候发生异常");

		boolean isTrue = true;
		
		DateFormat df = new SimpleDateFormat("HH");
		
		try {
			int integerHour = Integer.parseInt(df.format(date));
			
			if (integerHour >= 0 && integerHour <= 12) {
				isTrue = true;
			}
			else {
				isTrue = false;
			}
		}
		catch (NumberFormatException nfe) {
			log.error("判断是否为上午的时候发生异常", nfe);
		}
		
		return isTrue;
	}
	
	/**
	 * {@link #isAM(Date)}
	 * @return boolean
	 */
	public static boolean isAM() {
		return isAM(new Date());
	}
	@Deprecated
	public static String GeneDateSByC(int rollCnt, int dateType, boolean b) {
		Calendar cl = Calendar.getInstance();
		cl.add(dateType, rollCnt);
		SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		return dateFormat1.format(cl.getTime());
	}
	public static void main(String args [])
	{
		getCurrentWorkDays();
	}
	/**
	 * 返回当前日期加n天后的日期
	 * @author 林彬
	 * @return
	 */
	public static String getAdvanceDay(int advanceDay){
		SimpleDateFormat format = new   SimpleDateFormat("yyyyMMdd");  
		GregorianCalendar d = new GregorianCalendar();
		d.add(Calendar.DAY_OF_MONTH, advanceDay);
		return format.format(d.getTime());
	}
	
	/**
	 * 获取某月份的最大天
	 * @param MONTH 月份
	 * @param YEAR 年份
	 * @return int
	 */
	public static int getMaxDateForMonth(int MONTH, int YEAR){
		if(MONTH>7){
			if(MONTH%2==0)
				return 31;
			else
				return 30;
		}else{
			if(MONTH==2){
				if(YEAR%400==0||(YEAR%4==0&&YEAR%100!=0))
					return 29;
				else
					return 28;
			}else{
				if(MONTH%2==0)
					return 30;
				else
					return 31;
			}
		}
	}
	
	/**
	 * 获取当月的工作日天数
	 * @return
	 */
	public static int getCurrentWorkDays(){
		String input = current("yyyy-MM");
		int count = 0;
		int month = Integer.parseInt(input.substring(5, 7));
		int year = Integer.parseInt(input.substring(0, 4));
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH,  month - 1);
		cal.set(Calendar.DATE, 1);

		while(cal.get(Calendar.YEAR) == year && cal.get(Calendar.MONTH) < month){
			
			int day = cal.get(Calendar.DAY_OF_WEEK);
			
			if(!(day == Calendar.SUNDAY || day == Calendar.SATURDAY)){
				count++;
			}
			
			cal.add(Calendar.DATE, 1);
		}
		return count;
	}
	
	/**
	 * 获取指定月的工作日天数,格式yyyy-MM
	 * @return
	 */
	public static int getMonthWorkDays(String monthstr){
		String input = monthstr;
		int count = 0;
		int month = Integer.parseInt(input.substring(5, 7));
		int year = Integer.parseInt(input.substring(0, 4));
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH,  month - 1);
		cal.set(Calendar.DATE, 1);

		while(cal.get(Calendar.YEAR) == year && cal.get(Calendar.MONTH) < month){
			
			int day = cal.get(Calendar.DAY_OF_WEEK);
			
			if(!(day == Calendar.SUNDAY || day == Calendar.SATURDAY)){
				count++;
			}
			
			cal.add(Calendar.DATE, 1);
		}
		return count;
	}
	
	/**
	 * 获取当前月第一天，格式yyyy-MM-dd
	 * @return
	 */
	public static String getCurrentMonthFirstDay(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		//获取当前月第一天：
        Calendar c = Calendar.getInstance();   
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        return first;
	}
	
	/**
	 * 获取当前月最后一天，格式yyyy-MM-dd
	 * @return
	 */
	public static String getCurrentMonthLastDay(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		Calendar ca = Calendar.getInstance();   
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); 
        String last = format.format(ca.getTime());
        return last;
	}
	
	/**
	 * 传入参数格式yyyy-MM-dd
	 * 获取指定时间所在月的第一天，返回格式yyyy-MM-dd
	 * @return
	 */
	public static String getMonthFirstDay(String date){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		//获取当前月第一天：
        Calendar c = Calendar.getInstance();   
		Date time =null;
		try {
			time = format.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}//初始日期   
		c.setTime(time);//设置日历时间 
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        return first;
	}
	
	/**
	 * 传入参数格式yyyy-MM-dd
	 * 获取指定时间所在月的最后一天，返回格式yyyy-MM-dd
	 * @return
	 */
	public static String getMonthLastDay(String date){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		Calendar ca = Calendar.getInstance();  
		Date time =null;
		try {
			time = format.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}//初始日期   
        ca.setTime(time);//设置日历时间 
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); 
        String last = format.format(ca.getTime());
        return last;
	}
	
	/**
	 * @Title: getAllMonth
	 * @Description: 获取两个时间之间的所有月份
	 * @param startDay 格式'yyyy-MM-dd'
	 * @param endDay  格式'yyyy-MM-dd'
	 * @return 返回格式'yyyy-MM'
	 * @author linbin
	 * @throws
	 */
	public static String[] getAllMonth(String startDay,String endDay){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		Date date1 = null; // 开始日期
		Date date2 = null; // 结束日期
		try {
			date1 = format.parse(startDay);
			date2 = format.parse(endDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		//定义集合存放月份
	    List<String> list = new ArrayList<String>();
	    c1.setTime(date1);
	    c2.setTime(date2);
	    while (c1.compareTo(c2) <= 0) {
	    	// 开始日期加一个月直到等于结束日期为止
			Date ss = c1.getTime();
			String str = format.format(ss);
			str = str.substring(0, str.lastIndexOf("-"));
			list.add(str);
			c1.add(Calendar.MONTH, 1);
		}
	    //存放入数组
		String[] str = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			str[i] = (String) list.get(i);
		}
		System.out.println(Arrays.toString(str));
		return str;
	}
	
	/**
	 * 获取下一个月的第一天,返回格式yyyyMMdd
	 * @Title: nextMonthFirstDate
	 * @return 
	 * String
	 * @author linbin
	 * @throws
	 */
	public static String nextMonthFirstDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); 
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, 1);
        String time = format.format(calendar.getTime());
        return time;
    }
	
	/**
	 * 获取上一个月的第一天,返回格式yyyyMMdd
	 * @Title: nextMonthFirstDate
	 * @return 
	 * String
	 * @author linbin
	 * @throws
	 */
	public static String lastMonthFirstDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); 
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MONTH, -1);
        String time = format.format(calendar.getTime());
        return time;
    }
	
	/**
	 * @Title: getAllMonth
	 * @Description: 获取两个时间之间的所有天
	 * @param startDay 格式'yyyy-MM-dd'
	 * @param endDay  格式'yyyy-MM-dd'
	 * @return 返回格式'yyyy-MM-dd'
	 * @author linbin
	 * @throws
	 */
	public static String[] getAllDays(String startDay,String endDay){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		Date date1 = null; // 开始日期
		Date date2 = null; // 结束日期
		try {
			date1 = format.parse(startDay);
			date2 = format.parse(endDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		//定义集合存放月份
	    List<String> list = new ArrayList<String>();
	    c1.setTime(date1);
	    c2.setTime(date2);
	    while (c1.compareTo(c2) <= 0) {
	    	// 开始日期加一个月直到等于结束日期为止
			Date ss = c1.getTime();
			String str = format.format(ss);
			list.add(str);
			c1.add(Calendar.DATE, 1);
		}
	    //存放入数组
		String[] str = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			str[i] = (String) list.get(i);
		}
		System.out.println(Arrays.toString(str));
		return str;
	}
	
	/**
	 * 获取两个月之间的所有月份
	 * @param startTime yyyy-MM
	 * @param endTime yyyy-MM
	 * @return yyyy-MM
	 */
	public static List<String> getDatesFromStartToEnd(String startTime, String endTime) {
		List<String> allDates = new ArrayList<String>();
		int startYear = Integer.parseInt(startTime.split("-")[0]);
		int endYear = Integer.parseInt(endTime.split("-")[0]);
		if(endYear - startYear > 0) {
			for(int a = startYear; a < endYear; a++) {
				for(int b = 1; b <= 12; b++) {					
					allDates.add(String.valueOf(a) + '-' + String.valueOf(b < 10?"0"+b:b));
				}
			}
			int endMonth = Integer.parseInt(endTime.split("-")[1]);
			for(int i = 1; i <= endMonth; i++) {
				allDates.add(String.valueOf(endYear) + '-' + String.valueOf(i < 10?"0"+i:i));
			}
		} else {
			int startMonth = Integer.parseInt(startTime.split("-")[1]);
			int endMonth = Integer.parseInt(endTime.split("-")[1]);
			for(int a = startMonth; a <= endMonth; a++) {
				allDates.add(String.valueOf(endYear) + '-' + String.valueOf(a < 10?"0"+a:a));
			}
		}
		return allDates;
	}
	
}